NOTE
3.6 Redis hotkey
What a Redis hot key is, how to discover it, and how to mitigate it through key replication or local caching.
This is a historical learning note and may contain outdated or incomplete understanding.
1. What Is a Redis Hot Key?
A key whose read/write QPS exceeds the QPS bottleneck of a single Redis instance. Because it is a single key, Redis Cluster cannot distribute the pressure.
2. How to Discover a Redis Hot Key
- Business-service metrics reporting.
- Redis proxy information collection.
A key accessed more than 10K times per second is considered a hot key.
3. How to Solve a Redis Hot Key
3.1. Replicate the Key
Add a random number suffix to the key and distribute the copies across different Redis instances. Read-through caching is generally used.
// Number of Redis instances
const M = 16
// Multiple of the number of Redis instances (designed as needed, 2^n times, where n is generally an integer from 1 to 4)
const N = 2
func main() {
// Get a Redis instance
c, err := redis.Dial("tcp", "127.0.0.1:6379")
if err != nil {
fmt.Println("Connect to redis error", err)
return
}
defer c.Close()
hotKey := "hotKey:abc"
// Random number
randNum := GenerateRangeNum(1, N*M)
// Get a dispersed key for the hot key
tmpHotKey := hotKey + "_" + strconv.Itoa(randNum)
// Hot-key expiration time
expireTime := 50
// A random time value used to smooth the expiration time
randExpireTime := GenerateRangeNum(0, 5)
data, err := redis.String(c.Do("GET", tmpHotKey))
if err != nil {
data, err = redis.String(c.Do("GET", hotKey))
if err != nil {
data = GetDataFromDb()
c.Do("SET", "hotKey", data, expireTime)
c.Do("SET", tmpHotKey, data, expireTime + randExpireTime)
} else {
c.Do("SET", tmpHotKey, data, expireTime + randExpireTime)
}
}
}
In essence, this is replication. It can only solve read-performance problems, not write problems, and its readability is poor.
3.2. Local Cache
Each machine replicates a copy of the Redis hot key, with load balancing. In essence, this is also replication. It can solve the read problem and can also solve the write problem (with consistent-hash routing to the same node).
4. References
- 高频面试题-redis热key解决方案_哔哩哔哩_bilibili
- 谈谈redis的热key问题如何解决 - 脉脉
- 有赞透明多级缓存解决方案(TMC)
- A Detailed Explanation of the Detection and Processing of BigKey and HotKey in Redis - Alibaba Cloud Community
- 如何处理redis集群的hot key和big key - 云+社区 - 腾讯云
- 云数据库 Redis 查询实例热Key-API 文档-文档中心-腾讯云-腾讯云
- 云数据库 Redis 热 Key 分析-操作指南-文档中心-腾讯云-腾讯云
- 云数据库 Redis 5秒监控更新说明-操作指南-文档中心-腾讯云-腾讯云
- 云监控 告警服务-快速入门-文档中心-腾讯云-腾讯云
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub